package com.wulong.office;

import java.io.UnsupportedEncodingException;
import java.util.Formatter;

public class SpecialWordTest {
    public static void main(String[] args) throws UnsupportedEncodingException {
//        String name = "Wnt/β‑catenin我严";
//        String unicode = string2Unicode(name);
//        System.out.println(unicode);
//        System.out.println(unicode2String(unicode));

        String str = "a/β‑b" ;
        System.out.println(isHaveSpecial(str));
        String str1 = "cesi测试@&$#^&$(#" ;
        System.out.println(isHaveSpecial(str1));
    }

    /**
     * 判断str字符串是否包含gbk编码中不存在的字符
     * 例如：a/β‑b
     */
    public static boolean isHaveSpecial(String str){
        try {
            //首先对str进行解码，字符编码为gbk
            byte[] jiema= str.getBytes("gbk");
            //然后使用gbk编码对byte数组解码，在重新生成字符串
            //在此过程中，如果字符串中包含gbk编码之外的字符，则重新生成的字符串就会和源字符串不一致
            String bianma = new String(jiema,"gbk");
            return bianma.equals(str);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 字符串转换unicode
     */
    public static String string2Unicode(String str) {
        Formatter formatter = new Formatter();
        for (int i = 0; i < str.length(); i++) {
            formatter.format("\\u%04X", (int)str.charAt(i));
        }
        return formatter.toString();
    }

    /**
     * unicode 转字符串
     */
    public static String unicode2String(String unicode) {
        String ss[] = unicode.split("\\\\u");
        StringBuilder sb=new StringBuilder(ss.length-1);
        for (int i = 1; i < ss.length; i++) {
            sb.append((char)Integer.parseInt(ss[i], 16));
        }
        return sb.toString();
    }
}